import 'package:OASys/api/MeetingApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/entity/MeetingInfoVo.dart';
import 'package:OASys/entity/MeetingVo.dart';
import 'package:OASys/utils/strUtils.dart';
import 'package:OASys/views/icon/myIcons.dart';
import 'package:flutter/material.dart';

class MyMeeting extends StatefulWidget {
  @override
  _MyMeetingState createState() => _MyMeetingState();
}

class _MyMeetingState extends State<MyMeeting>
    with SingleTickerProviderStateMixin {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  GlobalKey<FormState> editKey = GlobalKey<FormState>();
  double _addPadding = 30;
  double _queryPadding = 30;
  bool flag = false;
  IconData actionIcon = MyIcons.spread;
  String loadText = "加载更多";

  int page = 1;
  int limit = 10;
  int total = 0;
  AnimationController _controller;
  List<MeetingVo> meetingVoList;
  MeetingVo andQuery = new MeetingVo();
  MeetingInfoVo info = new MeetingInfoVo();
  @override
  void initState() {
    super.initState();
    _getList();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 500),
    )..addListener(
        () {
          setState(() {
            _addPadding = 30 + 100 * _controller.value;
            _queryPadding = 30 + 200 * _controller.value;
          });
        },
      );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  // 更新数据
  void updateData() {
    setState(() {
      resetQueryData();
      _getList();
    });
  }

  // 重置查询条件
  void resetQueryData() {
    setState(() {
      loadText = "加载更多";
      page = 1;
      limit = 10;
      total = 0;
    });
  }

  void _getList() {
    MeetingApi().myMeeting(
      page,
      limit,
      success: (res) {
        setState(() {
          meetingVoList = res;
          page++;
          total += res.length;
        });
        res.forEach((element) {
          print(element.toJson().toString());
        });
      },
      error: (err) {
        print(err.code);
        print(err.message);
        showFailMessage(context);
      },
    );
  }

  Future toEdit(int id) async {
    print('编辑');
    Navigator.of(context, rootNavigator: true).pop();
    var result = await Navigator.of(context)
        .pushNamed('/meetingEdit', arguments: {"id": id});
    if (result == null || !result) {
      print('未添加');
    } else {
      updateData();
      print('添加成功');
    }
  }

  Future toAdd() async {
    var result = await Navigator.of(context).pushNamed('/meetingEdit');
    if (result == null || !result) {
      print('未添加');
    } else {
      updateData();
      print('添加成功');
    }
  }

  void deRemove(int id) {
    MeetingApi().remove(
      id,
      success: (res) {
        showSuccessMessage(context);
        updateData();
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  // 重置分页查询条件
  void resetQuerytData() {
    setState(() {
      loadText = "加载更多";
      page = 1;
      limit = 10;
      total = 0;
    });
  }

  void doQuery(context) {
    var form = formKey.currentState;
    form.save();
    print(andQuery.toJson());
    if (StrUtils.isBlank(andQuery.name) && StrUtils.isBlank(andQuery.place)) {
      showMessage(context, "请输入查询条件");
    } else {
      setState(() {
        if (StrUtils.isBlank(andQuery.name)) {
          andQuery.name = null;
        }
        if (StrUtils.isBlank(andQuery.place)) {
          andQuery.place = null;
        }
      });
      resetQuerytData();
      MeetingApi().list(
        page,
        limit,
        andQuery: andQuery,
        success: (res) {
          setState(() {
            meetingVoList = res;
            total += res.length;
            page++;
            if (total == 0) {
              loadText = "暂无数据";
            }
          });
        },
        error: (err) {
          print(err.code);
          showFailMessage(context);
        },
      );
      Navigator.of(context, rootNavigator: true).pop();
    }
  }

  void reset() {
    var form = formKey.currentState;
    form.reset();
    print('reset');
  }

  void editReset() {
    var form = editKey.currentState;
    form.reset();
  }

  void toSee(int id) {
    print("详情");
    Navigator.of(context, rootNavigator: true).pop();
    Navigator.of(context).pushNamed("/meetingDetail", arguments: {"id": id});
  }

  void setStatus(int id, int status) {
    if (status == 0) {
      print('开始会议');
      MeetingApi().start(id, success: (res) {
        showSuccessMessage(context);
        Navigator.of(context, rootNavigator: true).pop();
        updateData();
      }, error: (err) {
        print(err.code);
        showFailMessage(context);
      });
    } else if (status == 1) {
      print('结束');
      editSummary(id);
    } else {
      showMessage(context, '已结束');
    }
  }

  void endSave(int id) {
    var form = editKey.currentState;
    if (form.validate()) {
      form.save();
      setState(() {
        info.id = id;
        info.status = 2;
        MeetingApi().save(info, success: (res) {
          showSuccessMessage(context);
          Navigator.of(context, rootNavigator: true).pop();
          Navigator.of(context, rootNavigator: true).pop();
          updateData();
        }, error: (err) {
          print(err.code);
          showFailMessage(context);
        });
      });
    }
  }

  void editSummary(int id) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '查询会议',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              width: 300,
              child: Form(
                key: editKey,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier("会议总结:"),
                        Container(
                          width: 200,
                          child: FormText(
                            hintText: "请输入会议总结",
                            onSave: (value) {
                              info.summary = value;
                            },
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            RaisedButton(
              color: Color.fromRGBO(33, 150, 243, 1),
              child: Text('保 存'),
              onPressed: () {
                endSave(id);
              },
            ),
            RaisedButton(
              color: Color.fromRGBO(245, 108, 108, 1),
              child: Text('重 置'),
              onPressed: editReset,
            ),
          ],
        );
      },
    );
  }

// 显示搜索框
  showQuery() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '查询会议',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              width: 300,
              child: Form(
                key: formKey,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier("会议名称:"),
                        Container(
                          width: 200,
                          child: FormInput(
                            hintText: "请输入会议名称",
                            onSave: (value) {
                              andQuery.name = value;
                            },
                          ),
                        )
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier("会议地点:"),
                        Container(
                          width: 200,
                          child: FormInput(
                            hintText: "请输入会议地点",
                            onSave: (value) {
                              andQuery.place = value;
                            },
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            RaisedButton(
              color: Color.fromRGBO(33, 150, 243, 1),
              child: Text('查 询'),
              onPressed: () {
                doQuery(context);
              },
            ),
            RaisedButton(
              color: Color.fromRGBO(245, 108, 108, 1),
              child: Text('重 置'),
              onPressed: reset,
            ),
          ],
        );
      },
    );
  }

  String buildButtonName(int status) {
    String buttonName;
    switch (status) {
      case 0:
        buttonName = "开始会议";
        break;
      case 1:
        buttonName = "结束会议";
        break;
      default:
        buttonName = "已结束";
    }
    return buttonName;
  }

  onClick(MeetingVo item) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '会议信息',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(
                  children: [
                    InfoItem('会议名称', item.name),
                    InfoItem('状态', item.statusName),
                    InfoItem('类型', item.typeName),
                    InfoItem('主题', item.topic),
                    InfoItem('发起人', item.userName),
                    InfoItem('开始时间', item.beginTime),
                    InfoItem('结束时间', item.overTime),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            Visibility(
              visible: item.status < 2,
              child: RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text(buildButtonName(item.status)),
                onPressed: () {
                  setStatus(item.id, item.status);
                },
              ),
            ),
            Visibility(
              visible: item.status < 2,
              child: RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text('修 改'),
                onPressed: () {
                  toEdit(item.id);
                },
              ),
            ),
            RaisedButton(
              color: Color.fromRGBO(103, 194, 58, 1),
              textColor: Colors.white,
              child: Text('详 情'),
              onPressed: () {
                toSee(item.id);
              },
            ),
            RaisedButton(
              color: Color.fromRGBO(245, 108, 108, 1),
              child: Text('删 除'),
              onPressed: () {
                print('删除');
                deRemove(item.id);
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  // 加载更多
  void doLoad() {
    MeetingApi().myMeeting(
      page,
      limit,
      andQuery: andQuery,
      success: (res) {
        if (res == null || res.length == 0) {
          print('无数据');
          setState(() {
            loadText = "没有更多了";
          });
          return;
        }
        setState(() {
          meetingVoList.addAll(res);
          total += res.length;
          page++;
          loadText = "加载更多";
        });
        meetingVoList.forEach((element) {
          print(element.toJson());
        });
      },
      error: (err) {
        print(err.code);
        print(err.message);
        showMessage(context, err.message);
      },
    );
  }

  shrinkage() {
    setState(() {
      flag = !flag;
      if (flag) {
        actionIcon = MyIcons.shrink;
        _controller.forward();
      } else {
        actionIcon = MyIcons.spread;
        _controller.reverse();
      }
    });
  }

  /// 构建卡片
  Widget buildListItem(int index) {
    return FlatButton(
      child: Card(
        child: Container(
          width: 800,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ItemTitle(meetingVoList[index].name),
              ItemContext('状态：', meetingVoList[index].statusName),
              ItemContext('地点：', meetingVoList[index].place),
              ItemContext('主题：', meetingVoList[index].topic),
              ItemContext(
                '类型：',
                meetingVoList[index].typeName,
                dataColor: Colors.lightGreen,
              ),
              ItemContext('发起人：', meetingVoList[index].userName),
              ItemContext('开始时间：', meetingVoList[index].beginTime),
              ItemContext('结束时间：', meetingVoList[index].overTime),
            ],
          ),
        ),
      ),
      onPressed: () {
        onClick(meetingVoList[index]);
      },
    );
  }

  Widget buildLoadMore() {
    return FlatButton(
      child: Container(
        child: Text(
          loadText,
          style: TextStyle(color: Colors.blue, fontSize: 12),
        ),
      ),
      onPressed: () {
        doLoad();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.only(top: 10, bottom: 10),
          height: 720,
          child: ListView.builder(
              itemCount: total + 1,
              itemBuilder: (BuildContext context, int index) {
                if (index == total) {
                  return buildLoadMore();
                }
                return buildListItem(index);
              }),
        ),
        Positioned(
          right: _queryPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.yellow,
              child: Icon(
                MyIcons.query,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: () {
                showQuery();
              },
            ),
          ),
        ),
        Positioned(
          right: _addPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.green,
              child: Icon(
                MyIcons.add,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: () {
                toAdd();
              },
            ),
          ),
        ),
        Positioned(
          right: 30,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.blue,
              child: Icon(
                actionIcon,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: shrinkage,
            ),
          ),
        ),
      ],
    );
  }
}
